/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package huffman;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.LinkedHashMap;

/**
 *
 * @author ksz
 */
public class CompterFrequences {

    private String nomFichier;
    private LinkedHashMap frequence;
    private byte[] tamponLecture;

    public CompterFrequences(String nomFichier) {
        this.nomFichier = nomFichier;
        this.frequence = new LinkedHashMap();
        this.tamponLecture = new byte[256];
        construireDictionnaireDeFrequence();
    }

    private void construireDictionnaireDeFrequence() {

        try {

            BufferedInputStream entree = new BufferedInputStream(new FileInputStream(nomFichier));

            int tailleLu = entree.read(tamponLecture);
            
            while(tailleLu != -1) {

                for(int i = 0; i<tailleLu; i++) {
                    Character key = Character.valueOf((char) tamponLecture[i]);
                    if (frequence.containsKey(key)) {
                        frequence.put(key, ((Integer) frequence.get(key)) + 1);
                    } else {
                        frequence.put(key, new Integer(1));
                    }
                    //System.out.println("La clé : " + key + ", la prio : " + frequence.get(key));
                }

                tailleLu = entree.read(tamponLecture);
            }

        } catch (FileNotFoundException ex) {
            javax.swing.JOptionPane.showMessageDialog(null, "Le fichier est introuvable");
        } catch (IOException ex) {
            javax.swing.JOptionPane.showMessageDialog(null, "Impossible de lire le fichier");
        }

    }

    public LinkedHashMap getDictionnaireFrequences() {
        return frequence;
    }
}
